﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace 文华财经数据解析_donet8_.utils
{
    internal class DBUtil
    {
        // 执行查询，返回结果集
        public static List<T> ExecuteQuery<T>(string sql, string connectionString) 
        {
            var result = new List<T>();

            using (var connection = new MySqlConnection(connectionString))
            {
                connection.Open();

                using (var cmd = new MySqlCommand(sql, connection))
                {
                    // Execute the query and handle result set
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            // Check if T is a simple type
                            if (typeof(T) == typeof(string) || typeof(T).IsValueType)
                            {
                                // Add the first column value directly if T is a simple type
                                result.Add((T)Convert.ChangeType(reader[0], typeof(T)));
                                continue;
                            }


                            var entity = Activator.CreateInstance<T>();
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                var property = typeof(T).GetProperty(reader.GetName(i));
                                if (property != null && reader[i] != DBNull.Value)
                                {
                                    property.SetValue(entity, reader[i]);
                                }
                            }
                            result.Add(entity);
                        }
                    }
                }
            }

            return result;
        }





        public static int ExecuteNonQuery(string sql, string connectionString)
        {
            int ret = 0;
            using (var connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                using (var cmd = new MySqlCommand(sql, connection))
                {
                    ret = cmd.ExecuteNonQuery(); // 返回受影响的行数
                }
            }
            return ret;
        }
    }
}
